// 1. 要有组件

import {createWebHashHistory, createRouter} from 'vue-router';
import {tokenStore} from "@/store";

// 2. 定义一些路由（路径与组件之间的映射）
const routes = [
    // 后台管理员
    {name: 'login', path: '/login', component: () => import('@/components/Login.vue')},
    {
        name: 'index', path: '/', component: () => import('@/components/Index.vue'), children: [
            {name: 'charts', path: '/charts', component: () => import('@/components/Charts.vue')},
            {name: 'admin', path: '/admin', component: () => import('@/components/Admin.vue')},
            {name: 'logAdmin', path: '/logAdmin', component: () => import('@/components/LogAdmin.vue')},
            {name: 'doctor', path: '/doctor', component: () => import('@/components/Doctor.vue')},
            {name: 'patient', path: '/patient', component: () => import('@/components/Patient.vue')},
            {name: 'doctorSchedules', path: '/doctorSchedules', component: () => import('@/components/DoctorSchedules.vue')},
            {
                name: 'doctorSchedulesCalendar',
                path: '/doctorSchedulesCalendar',
                component: () => import('@/components/DoctorCalendar.vue')
            },
            {name: 'department', path: '/department', component: () => import('@/components/Department.vue')},
            {name: 'reserve', path: '/reserve', component: () => import('@/components/Reserve.vue')},
            {name: 'assistant', path: '/assistant', component: () => import('@/components/AiAssistant.vue')},
        ]
    },
];

// 3. 创建路由
const router = createRouter({
    history: createWebHashHistory(),    // 历史记录
    routes: routes,
});

// 路由是否已经加载
router.load = false;
// 全局前置守卫
router.beforeEach((to, from, next) => {
    const store = tokenStore()

    // 如果访问的不是登录页
    if (to.path !== '/login') {
        const token = store.token
        if (!token) {
            // 没有token，跳转到登录页
            next('/login')
        } else {
            next()
        }
    } else {
        next()
    }
})
// 4. 暴露
export default router